//
//  MacroTool.swift
//  d11
//
//  Created by peale on 2018/7/24.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
// MARK: ===================================变量宏定义=========================================//https://us-try.count.ly
public let kCountlyAppKey = "c4a6529c7671b457cc35a0c4d23fa0ac06a565cc"
public let kCountlyHost  = "http://countly.manbetlegend.com"

public let kNotificationToRegisterPage = "NotificationToRegisterPage"

public var isTest : Bool = false

//测试域名列表
//public var kMainIpArray: [String] = ["m.91manbet.net"]
//public var kMainIpArray: [String] = ["m.0359baopi.com"]
//public var kMainIpArray: [String] = ["m.mxappxpe.com"]
//m.nanjsky.com
//m.nbflq.com
//m.xagjdq.com
//m.lytnpx.com
//m.laomaweb.com
//m.kawosong.com
//m.jhjcom.com
//m.qznaw.com
//m.sxyyz.com
//m.zysnm.com
//正式域名列表
public var kMainIpArray: [String] = ["m.gzzyqhj.com",
                                     "m.chaofengxi.com",
                                     "m.crihg.com",
                                     "m.ourunhua.com",
                                     "m.nnhuachu.com",
                                     "m.cnyxwLkj.com",
                                     "m.xjdqwx.com",
                                     "m.dtsywy.com",
                                     "m.zhaqiuji.com",
                                     "m.zhswsh.com"]
    


//四十个主站包
let arrayIp = ["m.yhqiqiu.com",
               "m.baibaisui.com",
               "m.xuelanhua.com",
               "m.myerstudio.com",
               "m.0359baopi.com",
               "m.wohehua.com",
               "m.cdtl120.com",
               "m.iliuwei.com",
               "m.chuyou123.com",
               "m.ruciyou.com",
               "m.djbwgkbbkeqp.com",
               "m.dwpjaexm2rjg.com",
               "m.dndenw2hxw6n.com",
               "m.elp2yxespwqm.com",
               "m.eepnefayabr3.com",
               "m.fca2pgvpjzyy.com",
               "m.fkadmt943fmv.com",
               "m.fs5dbc4epxkt.com",
               "m.fxfjafhdznms.com",
               "m.gzr9hv3a9xsz.com",
               "m.ggxndaxqnkd3.com",
               "m.hevwrk69973h.com",
               "m.hxb7zpmdbxbm.com",
               "m.huwebh5vthht.com",
               "m.jlutmrmenxrc.com",
               "m.jkj8pc9gu9ae.com",
               "m.jxa2ffzgbnl9.com",
               "m.kmdz6fktcm3u.com",
               "m.kg7x3wqh2xce.com",
               "m.kyaqyzymuwxv.com",
               "m.lxzudmbby6pv.com",
               "m.lxsafrakf472.com",
               "m.mnj83m5ggff7.com",
               "m.mt3sfv8jtvkh.com",
               "m.nakx3lbtgxya.com",
               "m.nf8sj6sfubyr.com",
               "m.nztpkcamnavb.com",
               "m.nz2drpgmdfpd.com",
               "m.pwnyb2trfly9.com",
               "m.puag38uvr7hu.com"]
//获取对应线路错误提示
func getErrorString() -> String {
    let ip = kMainIpArray[0]
    let errorIndex = ["线路一","线路二","线路三","线路四","线路五","线路六","线路七","线路八","线路九","线路十","线路十一","线路十二","线路十三","线路十四","线路十五","线路十六","线路十七","线路十八","线路十九","线路二十","线路二十一","线路二十二","线路二十三","线路二十四","线路二十五","线路二十六","线路二十七","线路二十八","线路二十九","线路三十","线路三十一","线路三十二","线路三十三","线路三十四","线路三十五","线路三十六","线路三十七","线路三十八","线路三十九","线路四十"]
   var erorrString = ""
    for i in 0..<arrayIp.count {
        let item = arrayIp[i]
        if ip == item{
            if i < errorIndex.count{
                erorrString = errorIndex[i]
            }
            break
        }
    }
    return erorrString;
}

//获取对应线路版本提示
func getVersionString() -> String {
    let ip = kMainIpArray[0]
    let errorIndex = ["-1","-2","-3","-4","-5","-6","-7","-8","-9","-10","-11","-12","-13","-14","-15","-16","-17","-18","-19","-20","-21","-22","-23","-24","-25","-26","-27","-28","-29","-30","-31","-32","-33","-34","-35","-36","-37","-38","-39","-40"]
    var erorrString = ""
    for i in 0..<arrayIp.count {
        let item = arrayIp[i]
        if ip == item{
            if i < errorIndex.count{
                erorrString = errorIndex[i]
            }
            break
        }
    }
    return erorrString;
}

// MARK: 系统相关
/// Info
public let kAppBundleInfoVersion = Bundle.main.infoDictionary ?? Dictionary()
/// plist:  AppStore 使用VersionCode 1.0.1
public let kAppBundleVersion = (kAppBundleInfoVersion["CFBundleShortVersionString" as String] as? String ) ?? ""
/// plist: 例如 1
public let kAppBundleBuild = (kAppBundleInfoVersion["CFBundleVersion"] as? String ) ?? ""
public let kAppDisplayName = (kAppBundleInfoVersion["CFBundleDisplayName"] as? String ) ?? ""

// MARK: 系统相关
public let kiOSBase = 8.0
public let kOSGreaterOrEqualToiOS8 = ( (Double(UIDevice.current.systemVersion) ?? kiOSBase) > 8.0 ) ? true : false;
public let kOSGreaterOrEqualToiOS9 = ((Double(UIDevice.current.systemVersion) ?? kiOSBase) >= 9.0 ) ? true : false;
public let kOSGreaterOrEqualToiOS10 = ((Double(UIDevice.current.systemVersion) ?? kiOSBase) >= 10.0 ) ? true : false;
public let kOSGreaterOrEqualToiOS11 = ((Double(UIDevice.current.systemVersion) ?? kiOSBase) >= 11.0 ) ? true : false;

//设备宽高、机型
public let kScreenHeight = UIScreen.main.bounds.size.height
public let kScreenWidth = UIScreen.main.bounds.size.width
//设备像素宽高
public let kScreenModeWidth = UIScreen.main.currentMode?.size.width
public let kScreenModeHeight = UIScreen.main.currentMode?.size.height

public let kStatusBarheight = UIApplication.shared.statusBarFrame.size.height
public let kNavBarHeight_StatusHeight: ((UIViewController)-> CGFloat) = {(vc : UIViewController ) -> CGFloat in
    weak var weakVC = vc;
    var navHeight = weakVC?.navigationController?.navigationBar.bounds.size.height ?? 0.0
    return (navHeight + kStatusBarheight)
}

// iPhone4
public let isIphone4 = kScreenHeight  < 568 ? true : false
// iPhone 5
public let isIphone5 = kScreenHeight  == 568 ? true : false
// iPhone 6
public let isIphone6 = kScreenHeight == 667 ? true : false
// iphone 6P
public let isIphone6P = (kScreenHeight == 736 && kScreenWidth == 414) ? true : false
// iphone X XS
public let isIphoneX = (kScreenHeight == 812 && kScreenWidth == 375) ? true : false
// iphone XR
public let isIphoneXR = (kScreenModeWidth == 828 && kScreenModeHeight == 1792) ? true : false
// iphone XS Max
public let isIphoneXS_Max = (kScreenModeWidth == 1242 && kScreenModeHeight == 2688) ? true : false

// iphone X 系列
public let isIphoneX_Series = isIphoneX || isIphoneXR || isIphoneXS_Max ? true : false

// navigationBarHeight
public let kNavigationBarHeight : CGFloat = isIphoneX_Series ? 88 : 64
public let kNavigationBarTop : CGFloat = isIphoneX_Series ? 24 : 0
public let kStatusBarHeight : CGFloat = UIApplication.shared.statusBarFrame.height
// tabBarHeight
public let kTabBarHeight : CGFloat = isIphoneX_Series ? 49 + 34 : 49
public let kTabBarBottom : CGFloat = isIphoneX_Series ? 34 : 0
public let kIsIpad  =  UIDevice.current.userInterfaceIdiom == .pad ? true :false
// MARK: ============================================================================
// MARK: Dictory Array Strig Object 闭包方式
///过滤null对象
public let kFilterNullOfObj:((Any)->Any?) = {(obj: Any) -> Any? in
    if obj is NSNull {
        return nil
    }
    return obj
}

///过滤null的字符串，当nil时返回一个初始化的空字符串
public let kFilterNullOfString:((Any)->String) = {(obj: Any) -> String in
    if obj is String {
        return obj as! String
    }
    return ""
}


/// 过滤null的数组，当nil时返回一个初始化的空数组
public let kFilterNullOfArray:((Any)->Array<Any>) = {(obj: Any) -> Array<Any> in
    if obj is Array<Any> {
        return obj as! Array<Any>
    }
    return Array()
}


/// 过滤null的字典，当为nil时返回一个初始化的字典
public let kFilterNullOfDictionary:((Any) -> Dictionary<AnyHashable, Any>) = {( obj: Any) -> Dictionary<AnyHashable, Any> in
    if obj is Dictionary<AnyHashable, Any> {
        return obj as! Dictionary<AnyHashable, Any>
    }
    return Dictionary()
}


// MARK: ============================================================================
// MARK: 设置Nib、Stryboard、UIImage

/// 根据imageName创建一个UIImage
public let imageNamed:((String) -> UIImage? ) = { (imageName : String) -> UIImage? in
    return UIImage.init(named: imageName)
}


/// 图片地址
public let kMainUrl:((String) -> URL? ) = { (imagePath : String) -> URL? in
    if imagePath  != "" {
        let imageUrl: URL = URL(string: imagePath)!
        return URL(string:"\(RequestHelper.requestScheme)://\(imageUrl.host!)\(imageUrl.path)")!
    }else{
        let domain : String = UserDefaults.standard.value(forKey: DefaultKey.USER_DOMAIN) as? String ?? ""
        return URL.init(string:"\(RequestHelper.requestScheme)://\(domain)")!
    }
}

// MARK: ============================================================================
// MARK: 设置颜色
/// 设置颜色值
public let HexRGB:((Int) -> UIColor) = { (rgbValue : Int) -> UIColor in
    return HexRGBAlpha(rgbValue,1.0)
    
}

/// 通过 十六进制与alpha来设置颜色值  （ 样式： 0xff00ff ）
public let HexRGBAlpha:((Int,Float) -> UIColor) = { (rgbValue : Int, alpha : Float) -> UIColor in
    return UIColor(red: CGFloat(CGFloat((rgbValue & 0xFF0000) >> 16)/255), green: CGFloat(CGFloat((rgbValue & 0xFF00) >> 8)/255), blue: CGFloat(CGFloat(rgbValue & 0xFF)/255), alpha: CGFloat(alpha))
}


/// 通过 red 、 green 、blue 、alpha 颜色数值
public let RGBAlpa:((Float,Float,Float,Float) -> UIColor ) = { (r: Float, g: Float , b: Float , a: Float ) -> UIColor in
    return UIColor.init(red: CGFloat(CGFloat(r)/255.0), green: CGFloat(CGFloat(g)/255.0), blue: CGFloat(CGFloat(b)/255.0), alpha: CGFloat(a))
}

//设置根目录为登录页面
func setRootLoginVC() ->Void{
    
    LoginViewController.loginIfNeedController(currentController: (UIApplication.shared.keyWindow?.rootViewController)!, succeedBlock: {
        
    })
}
//获取当前的vc
func funcgetCurrentViewC() -> UIViewController{
    let vc = UIApplication.shared.keyWindow?.rootViewController
    return findBestViewController(vc: vc!)
}
func findBestViewController(vc : UIViewController) -> UIViewController {
    if vc.presentedViewController != nil {
        return findBestViewController(vc: vc.presentedViewController!)
    } else if vc.isKind(of:UISplitViewController.self) {
        let svc = vc as! UISplitViewController
        if svc.viewControllers.count > 0 {
            return findBestViewController(vc: svc.viewControllers.last!)
        } else {
            return vc
        }
    } else if vc.isKind(of: UINavigationController.self) {
        let nvc = vc as! UINavigationController
        if nvc.viewControllers.count > 0 {
            return findBestViewController(vc: nvc.topViewController!)
        } else {
            return vc
        }
    } else if vc.isKind(of: UITabBarController.self) {
        let tvc = vc as! UITabBarController
        if (tvc.viewControllers?.count)! > 0 {
            return findBestViewController(vc: tvc.selectedViewController!)
        } else {
            return vc
        }
    } else {
        return vc
    }
}

func checkEmail(email: String)->Bool {
    //        "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
    let emailString = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
    let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailString)
    return emailPredicate.evaluate(with: email)
    
}
extension String {
    func md5() -> String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        free(result)
        return String(format: hash as String)
    }
}
func stringToMD5(string:String) ->String{
    let str = string.cString(using: String.Encoding.utf8)
    let strLen = CUnsignedInt(string.lengthOfBytes(using: String.Encoding.utf8))
    let digestLen = Int(CC_MD5_DIGEST_LENGTH)
    let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
    CC_MD5(str!, strLen, result)
    let hash = NSMutableString()
    for i in 0 ..< digestLen {
        hash.appendFormat("%02x", result[i])
    }
    result.deinitialize(count: digestLen)
    return String(format: hash as String)
}
